package com.csnf.Dao;

import com.csnf.entity.UserAuthors;
import com.csnf.entity.UserBooks;
import com.csnf.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AuthoreDao {
    public List<UserAuthors> getAuthore() throws Exception {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from authors ";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn,sql);
        ResultSet rs = ps.executeQuery();
        List<UserAuthors> authorsList = new ArrayList<>();
        while (rs.next()) {
            UserAuthors authors = JdbcUtil.invokeObject(rs,UserAuthors.class);
            authorsList.add(authors);
        }
        JdbcUtil.close(conn,ps,rs);
        return authorsList;
    }

    public UserAuthors getAuthoreById(Integer author_id) throws Exception {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select * from authors where author_id=?";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn,sql,author_id);
        ResultSet rs = ps.executeQuery();
        UserAuthors authors = new UserAuthors();
        if (rs.next()) {
            authors = JdbcUtil.invokeObject(rs,UserAuthors.class);
        }
        BooksDao booksDao = new BooksDao();
        List<UserBooks> booksList = booksDao.getAllBooksByName(String.valueOf(authors.getAuthor_id()));
        authors.setBooksList(booksList);
        return authors;
    }
}
